package de.baumann.browser.api.net.base;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;

public class IntegerTypeAdapter extends TypeAdapter<Integer> {
    @Override
    public void write(JsonWriter out, Integer value) throws IOException {
        if (value == null) {
            value = 0;
        }
        out.value(String.valueOf(value));
    }

    @Override
    public Integer read(JsonReader in) throws IOException {

        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return 0;
        }

        if (in.peek() == JsonToken.STRING) {
            try {
                return Integer.parseInt(in.nextString());
            } catch (NumberFormatException e) {
                return 0;
            }
        }else{
            return in.nextInt();
        }
    }
}
